package com.b2b.util;

import com.b2b.model.WorkAdministratorUserDto;
import com.b2b.model.WorkOrderDto;
import com.b2b.model.entity.WorkOrder;
import com.b2b.service.WorkAdministratorUserService;
import com.b2b.service.WorkOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WorKOrderUtil {

    private final WorkOrderService workOrderService;
    private final WorkAdministratorUserService workAdministratorUserService;
    @Autowired
    public WorKOrderUtil(WorkOrderService workOrderService,WorkAdministratorUserService workAdministratorUserService){
        this.workOrderService = workOrderService;
        this.workAdministratorUserService = workAdministratorUserService;
    }

    public Integer insertWorkOrder(WorkOrderDto workOrderDto){
        WorkOrder workOrder = getWorkOrder(workOrderDto);
        Integer count = workOrderService.insert(workOrder);
        if (count <= 0){
            return count;
        }
        count = workOrder.getWorkOrderId();
        WorkAdministratorUserDto workAdministratorUserDto = new WorkAdministratorUserDto();
        workAdministratorUserDto.setUserId(workOrderDto.getUserId());
        workAdministratorUserDto.setWorkOrderId(count);
        Integer count2 = workAdministratorUserService.insert(workAdministratorUserDto);
        if (count2 <= 0){
            return count2;
        }
        return count;
    }

    public Integer updateWorkOrder(WorkOrderDto workOrderDto){
        WorkAdministratorUserDto workAdministratorUserDto = new WorkAdministratorUserDto();
        workAdministratorUserDto.setWorkOrderId(workOrderDto.getWorkOrderId());
        workAdministratorUserDto = workAdministratorUserService.selectOne(workAdministratorUserDto);

        Integer count =null ;

        if (workAdministratorUserDto.getAdministratorId() == null){
            workAdministratorUserDto.setAdministratorId(workOrderDto.getAdministratorId());
            count = workAdministratorUserService.updateByPrimaryKeySelective(workAdministratorUserDto);
        }
        if (count <0 ){
            return count;
        }else {
            WorkOrder workOrder = getWorkOrder(workOrderDto);
            count = workOrderService.updateByPrimaryKeySelective(workOrder);
            return count;
        }
    }
    public WorkOrder getWorkOrder(WorkOrderDto workOrderDto){
        WorkOrder workOrder = new WorkOrder();
        workOrder.setWorkOrderId(workOrderDto.getWorkOrderId());
        workOrder.setDescription(workOrderDto.getDescription());
        workOrder.setFeedback(workOrderDto.getFeedback());
        workOrder.setImageUrl(workOrderDto.getImageUrl());
        workOrder.setTime(workOrderDto.getTime());
        workOrder.setState(workOrderDto.getState());

        return workOrder;
    }

}
